import os
import urllib
from pathlib import Path

from flask import jsonify, current_app
from flask_restful import reqparse, Resource

from project_name.base import User_DIR
from project_name.ext.database import db
from project_name.models import accounts
from project_name.utils import get_real_path


class UpdatePasswordResource(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username', type=str, required=True)
        parser.add_argument('oldPassword', type=str, required=True)
        parser.add_argument('newPassword', type=str, required=True)
        args = parser.parse_args()
        try:
            user = accounts.query.filter_by(username=args['username']).first()
            if user:
                if user.password != args['oldPassword']:
                    return jsonify({"code": 401, "message": "旧密码错误", "data": None})
                user.password = args['newPassword']
                db.session.commit()
                return jsonify({"code": 200, "message": "修改密码成功", "data": user})
            else:
                return jsonify({"code": 404, "message": "用户不存在", "data": None})
        except Exception as e:
            return jsonify({"code": 500, "message": str(e), "data": None})


class LoginResource(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username', type=str, required=True, help='username is required')
        parser.add_argument('password', type=str, required=True, help='password is required')
        data = parser.parse_args()

        username = str(data['username'])
        password = str(data['password'])
        Accounts = accounts.query.filter_by(username=username).first()
        if Accounts:
            if password == Accounts.password:
                return jsonify({"code": 200, "data": {
                    "id": Accounts.id,
                    "username": Accounts.username,
                    "idType": Accounts.id_type,
                    "parentId": Accounts.parent_account_id,
                }})
            else:
                return jsonify({"code": 404, "message": "用户名或密码错误"})
        else:
            return jsonify({"code": 404, "message": "用户不存在"})


class GetFileResource(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('path', type=str, required=True, help='path is required')
        parser.add_argument('username', type=str, required=True, help='username is required')
        data = parser.parse_args()

        try:
            full_path = os.path.join(User_DIR, data['username'])
            target_path = os.path.join(full_path, data['path'])

            if not os.path.exists(target_path):
                return jsonify({"error": "路径不存在"}), 404

            items = os.listdir(target_path)
            files = []
            folders = []

            for item in items:
                item_path = os.path.join(target_path, item)
                is_folder = os.path.isdir(item_path)

                file_info = {
                    "name": item,
                    "type": "directory" if is_folder else item.split('.')[-1],
                }
                if is_folder:
                    folders.append(file_info)
                    files.append(file_info)
                else:
                    if file_info['type'] in ['jpg', 'jpeg', 'png']:
                        file_info[
                            'url'] = f"${current_app.config['resource_url']}/getFile?path={urllib.parse.quote(os.path.relpath(os.path.join(target_path, item), full_path))}&username={urllib.parse.quote(data['username'])}"
                    files.append(file_info)

            return jsonify({
                "folders": folders,
                "files": files
            })
        except Exception as e:
            return jsonify({"error": str(e)}), 500


class GetFileListResource(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('path', type=str, required=True, help='path is required')
        data = parser.parse_args()
        try:
            path = get_real_path(data['path'], ",")
            if path == os.sep:
                path = 'Admin'
            full_path = Path(current_app.static_folder) / path
            if not os.path.exists(full_path):
                return jsonify({"code": 404, "data": "", "message": "路径不存在"})

            dirs = []
            for path in full_path.iterdir():
                if path.is_dir():
                    dirs.append({
                        "name": path.name,
                        "type": "directory",
                    })

            return jsonify({"code": 200, "data": dirs, "message": "success"})

        except Exception as e:
            return jsonify({"code": 400, "data": "", "message": str(e)})
